import classNames from 'classnames'
import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'

export default function Textarea({
  maxLength = 100,
  value,
  onChange,
  className,
  ...rest
}) {
  const [count, setCount] = useState(value || '')

  const handleChange = (e) => {
    setCount(e.target.value)
    onChange?.(e)
  }
  const textareaRef = useRef(null)
  useEffect(() => {
    textareaRef.current.focus()
    textareaRef.current.setSelectionRange(-1, -1)
  }, [])

  return (
    <div className={styles.root}>
      <textarea
        {...rest}
        className={classNames('textarea', className)}
        value={value}
        onChange={handleChange}
        maxLength={maxLength}
        ref={textareaRef}
      ></textarea>

      {/* 字数统计 */}
      <div className="count">
        {count.length}/{maxLength}
      </div>
    </div>
  )
}
